package viv.karaoke.book;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.provider.Contacts.SettingsColumns;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.SearchView.OnQueryTextListener;

public class MainActivity extends Activity
{
	private MenuItem mSpinnerItem = null;
//	private MenuItem mSearchItem = null;

//	private EditText mSearch = null;
//	private Button mDelete = null;
	
	public long userId;
	public String UserName;
	
	public SearchView mSearchView;
	public String mQuery = "";

	private SongDataSource datasource;
		
	private class MyTabListener implements ActionBar.TabListener
	{
		private Fragment mFragment;
		private final Activity mActivity;
		private final String mFragName;
		

		public MyTabListener( Activity activity, String fragName )
		{
			mActivity = activity;
			mFragName = fragName;
		}

		@Override
		public void onTabReselected( Tab tab, FragmentTransaction ft )
		{
			// TODO Auto-generated method stub
			if (mFragment == null) {
				
				mFragment = Fragment.instantiate( mActivity, mFragName );
				ft.add( android.R.id.content, mFragment );
			}
			else
			{
				ft.replace(android.R.id.content, mFragment);
			}
					
		}

		@Override
		public void onTabSelected( Tab tab, FragmentTransaction ft )
		{
			mFragment = Fragment.instantiate( mActivity, mFragName );
			ft.add( android.R.id.content, mFragment );
		}

		@Override
		public void onTabUnselected( Tab tab, FragmentTransaction ft )
		{
			ft.remove( mFragment );
			mFragment = null;
		}
	}

	private ActionMode.Callback mCallback = new ActionMode.Callback()
	{
		private Fragment settingFragment;
		
		@Override
		public boolean onPrepareActionMode( ActionMode mode, Menu menu )
		{
			return false;
		}

		@Override
		public void onDestroyActionMode( ActionMode mode )
		{
			// TODO Auto-generated method stub
//			FragmentTransaction transaction = getFragmentManager().beginTransaction();
//			transaction.remove(settingFragment);
//			settingFragment = null;
		}

		@Override
		public boolean onCreateActionMode( ActionMode mode, Menu menu )
		{
			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate( R.menu.actionmode, menu );
			MenuItem item = menu.findItem( R.id.action_text );
			View v = item.getActionView();
			if( v instanceof TextView )
			{
				((TextView)v).setText( R.string.setting_title);
			}
			
			settingFragment = new SettingFragment();
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
//			getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
//			getFragmentManager().findFragmentById(id)findFragmentByTag(tag)
			
			transaction.replace(android.R.id.content, settingFragment);
		    transaction.addToBackStack(null);
		    transaction.show(settingFragment);
		    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		    transaction.commit();
		    
			return true;
		}

		@Override
		public boolean onActionItemClicked( ActionMode mode, MenuItem item )
		{
			boolean ret = false;
			if(item.getItemId() == R.id.actionmode_cancel) {
				mode.finish();
				
				Activity currentActivity = settingFragment.getActivity();
				
				FragmentTransaction transaction = getFragmentManager().beginTransaction();
				transaction.remove(settingFragment);
				settingFragment = null;
				transaction.commit();
						        
//				currentActivity.getActionBar().setSelectedNavigationItem(1);
				currentActivity.getActionBar().setSelectedNavigationItem(0);
				
				ret = true;
			}
			return ret;
		}
	};

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );

		datasource = new SongDataSource(this);
  	    datasource.open();
  	    
  	    datasource.createSong("Dong Song Lo Dang", "Bang Kieu", "Tung ngon tay kheo nhung nu hoa trang", "will update later!");
	    datasource.createSong("Chuyen Tinh Cua Bien", "Tung Duong", "Ngay xua bien khong co cat nhu bay gio", "will update later!");
	    datasource.createSong("Em ve tinh khoi", "Tran Thu Ha", "Ban tay em la canh sen thom uop trong vung dem mai toc", "will update later!");
	    datasource.createSong("Anh", "Tran Tam & My Le", "abc", "will update later!");
	    datasource.createSong("Anh Biet Em Di Chang Tro Ve", "Vu Khanh", "abc", "will update later!");
	    datasource.createSong("Anh Chang Da Nghi", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chang Dep Trai", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chi La Hinh Bong Cua Nguoi Khac", "Lam Vu", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Da Nhat Yen", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Elvis Phuong", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Khanh Ly", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Lam Thuy Van", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Quang Linh", "abc", "will update later!");
	    datasource.createSong("Dong Song Lo Dang", "Bang Kieu", "Tung ngon tay kheo nhung nu hoa trang", "will update later!");
	    datasource.createSong("Chuyen Tinh Cua Bien", "Tung Duong", "Ngay xua bien khong co cat nhu bay gio", "will update later!");
	    datasource.createSong("Em ve tinh khoi", "Tran Thu Ha", "Ban tay em la canh sen thom uop trong vung dem mai toc", "will update later!");
	    datasource.createSong("Anh", "Tran Tam & My Le", "abc", "will update later!");
	    datasource.createSong("Anh Biet Em Di Chang Tro Ve", "Vu Khanh", "abc", "will update later!");
	    datasource.createSong("Anh Chang Da Nghi", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chang Dep Trai", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chi La Hinh Bong Cua Nguoi Khac", "Lam Vu", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Da Nhat Yen", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Elvis Phuong", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Khanh Ly", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Lam Thuy Van", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Quang Linh", "abc", "will update later!");
	    datasource.createSong("Dong Song Lo Dang", "Bang Kieu", "Tung ngon tay kheo nhung nu hoa trang", "will update later!");
	    datasource.createSong("Chuyen Tinh Cua Bien", "Tung Duong", "Ngay xua bien khong co cat nhu bay gio", "will update later!");
	    datasource.createSong("Em ve tinh khoi", "Tran Thu Ha", "Ban tay em la canh sen thom uop trong vung dem mai toc", "will update later!");
	    datasource.createSong("Anh", "Tran Tam & My Le", "abc", "will update later!");
	    datasource.createSong("Anh Biet Em Di Chang Tro Ve", "Vu Khanh", "abc", "will update later!");
	    datasource.createSong("Anh Chang Da Nghi", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chang Dep Trai", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chi La Hinh Bong Cua Nguoi Khac", "Lam Vu", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Da Nhat Yen", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Elvis Phuong", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Khanh Ly", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Lam Thuy Van", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Quang Linh", "abc", "will update later!");
	    datasource.createSong("Dong Song Lo Dang", "Bang Kieu", "Tung ngon tay kheo nhung nu hoa trang", "will update later!");
	    datasource.createSong("Chuyen Tinh Cua Bien", "Tung Duong", "Ngay xua bien khong co cat nhu bay gio", "will update later!");
	    datasource.createSong("Em ve tinh khoi", "Tran Thu Ha", "Ban tay em la canh sen thom uop trong vung dem mai toc", "will update later!");
	    datasource.createSong("Anh", "Tran Tam & My Le", "abc", "will update later!");
	    datasource.createSong("Anh Biet Em Di Chang Tro Ve", "Vu Khanh", "abc", "will update later!");
	    datasource.createSong("Anh Chang Da Nghi", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chang Dep Trai", "Chau Gia Kiet", "abc", "will update later!");
	    datasource.createSong("Anh Chi La Hinh Bong Cua Nguoi Khac", "Lam Vu", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Da Nhat Yen", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Elvis Phuong", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Khanh Ly", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Lam Thuy Van", "abc", "will update later!");
	    datasource.createSong("Anh Cho Em Mua Xuan", "Quang Linh", "abc", "will update later!");
	    
  	    
		int mode = ActionBar.NAVIGATION_MODE_TABS;

		if (savedInstanceState != null)
		{
			mode = savedInstanceState.getInt( "mode",
					ActionBar.NAVIGATION_MODE_TABS );
		}
		ActionBar ab = getActionBar();
		ab.setDisplayShowTitleEnabled( false );
		if (mode == ActionBar.NAVIGATION_MODE_TABS)
		{
			setTabNavigation( ab );
		} else
		{
			setListNavigation( ab );
		}
	}

	@Override
	protected void onSaveInstanceState( Bundle outState )
	{
		outState.putInt( "mode", getActionBar().getNavigationMode() );
		super.onSaveInstanceState( outState );
	}

	@Override
	public boolean onCreateOptionsMenu( Menu menu )
	{
		getMenuInflater().inflate( R.menu.main, menu );
		mSpinnerItem = menu.findItem( R.id.menu_spinner );
		setupSpinner( mSpinnerItem );
//		mSearchItem = menu.findItem( R.id.menu_search );
//		mSearchItem
//				.setVisible( getActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS );
//		mSearch = (EditText) mSearchItem.getActionView().findViewById(
//				R.id.search );
//		mDelete = (Button) mSearchItem.getActionView().findViewById(
//				R.id.delete );
//		mDelete.setVisibility( mSearch.getText().length() > 0 ? View.VISIBLE
//				: View.GONE );
//		mSearch.addTextChangedListener( new TextWatcher()
//		{
//			@Override
//			public void onTextChanged( CharSequence s, int start, int before,
//					int count )
//			{
//			}
//
//			@Override
//			public void beforeTextChanged( CharSequence s, int start,
//					int count, int after )
//			{
//			}
//
//			@Override
//			public void afterTextChanged( Editable s )
//			{
////				mDelete.setVisibility( s.length() > 0 ? View.VISIBLE
////						: View.GONE );
//			}
//		} );
		
		// handle Search
		mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();        
		
		mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				mSearchView.clearFocus();
				mQuery = query;
			    			    
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				
				try
				{
					mQuery = newText;
					Fragment newFragment = new SongFragment();
				    FragmentTransaction transaction = getFragmentManager().beginTransaction();
				    transaction.replace(android.R.id.content, newFragment);
				    transaction.addToBackStack(null);
				    transaction.commit();
				}
				catch(Exception ex)
				{
				}
				
				return false;
			}
		});
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected( MenuItem item )
	{
		boolean ret;
		if (item.getItemId() == R.id.menu_about)
		{
			// Handle Settings
			ret = true;
		} else if (item.getItemId() == R.id.menu_toggle)
		{
			ActionBar ab = getActionBar();
			if (ab.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS)
			{
				setListNavigation( ab );
//				mSearchItem.setVisible( false );
			} else
			{
				setTabNavigation( ab );
//				mSearchItem.setVisible( true );
			}
			ret = true;
		} else if( item.getItemId() == R.id.menu_settings)
		{
			startActionMode( mCallback );
			
			ret = true;
		} else
		{
			ret = super.onOptionsItemSelected( item );
		}
		return ret;
	}

	private void setTabNavigation( ActionBar actionBar )
	{
		actionBar.removeAllTabs();
		actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );
		actionBar.setTitle( R.string.app_name );

		Tab tab = actionBar
				.newTab()
				.setText( R.string.Songs )
				.setTabListener(
						new MyTabListener( this, SongFragment.class.getName() ) );
		actionBar.addTab( tab );

		tab = actionBar
				.newTab()
				.setText( R.string.Favourite )
				.setTabListener(
						new MyTabListener( this, FavouriteFragment.class.getName() ) );
		actionBar.addTab( tab );
		if (mSpinnerItem != null)
		{
			mSpinnerItem.setVisible( false );
		}
	}

	private void setListNavigation( ActionBar actionBar )
	{
		actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_LIST );

		final List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put( "title", getString( R.string.Songs ) );
		map.put( "fragment",
				Fragment.instantiate( this, SongFragment.class.getName() ) );
		data.add( map );
		map = new HashMap<String, Object>();
		map.put( "title", getString( R.string.Favourite ) );
		map.put( "fragment",
				Fragment.instantiate( this, FavouriteFragment.class.getName() ) );
		data.add( map );
		SimpleAdapter adapter = new SimpleAdapter( this, data,
				android.R.layout.simple_spinner_dropdown_item,
				new String[] { "title" }, new int[] { android.R.id.text1 } );
		actionBar.setListNavigationCallbacks( adapter,
				new OnNavigationListener()
				{
					@Override
					public boolean onNavigationItemSelected( int itemPosition,
							long itemId )
					{
						Map<String, Object> map = data.get( itemPosition );
						Object o = map.get( "fragment" );
						if (o instanceof Fragment)
						{
							FragmentTransaction tx = getFragmentManager()
									.beginTransaction();
							tx.replace( android.R.id.content, (Fragment) o );
							tx.commit();
						}
						return true;
					}
				} );
		if (mSpinnerItem != null)
		{
			setupSpinner( mSpinnerItem );
		}
	}

	private void setupSpinner( MenuItem item )
	{
		item.setVisible( getActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST );
		View view = item.getActionView();
		if (view instanceof Spinner)
		{
			Spinner spinner = (Spinner) view;
			spinner.setAdapter( ArrayAdapter.createFromResource( this,
					R.array.spinner_data,
					android.R.layout.simple_spinner_dropdown_item ) );
		}
	}

//	public void delete( View v )
//	{
//		if (mSearch != null)
//		{
//			mSearch.setText( "" );
//		}
//	}
}
